<template>
  <div class="zy-content pb50">
    <back-level :go-page="backPage" />
    <Card title="保养计划" class="detail-content-layout mt16">
      <div class="basic-info">
        <div class="basic-info-body">
          <Row style="border-top: 1px solid #eee;border-bottom: 1px solid #eee">
            <Col span="12">
            <Row>
              <Col class="basic-info-body-label" span="24">保养计划</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.servicingPlanName || '--' }}</Col>
            </Row>
            </Col>
            <Col span="12">
            <Row>
              <Col class="basic-info-body-label" span="24">保养方式</Col>
              <Col class="basic-info-body-item" span="24">{{
                dataArr.maintainType == 1 ? '定期' : dataArr.maintainType == 2 ? '计数' : '计时' }}</Col>
            </Row>
            </Col>
          </Row>
        </div>
      </div>
    </Card>
    <Card title="保养对象" class="detail-content-layout mt16">
      <div class="basic-info">
        <div class="basic-info-body">
          <Row style="border-top: 1px solid #eee;border-bottom: 1px solid #eee">
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">模具名称</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.mmoldName || '--' }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">模具编号</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.mmoldCode || '--' }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">模具型号</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.moldModel || '--' }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">具体位置</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.location || '--' }}</Col>
            </Row>
            </Col>
          </Row>
          <Row style="border-top: 1px solid #eee;border-bottom: 1px solid #eee">
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">材料厚度</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.thickness || '--' }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">制造年月</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.productDate || '--' }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">外形尺寸</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.mmoldSize || '--' }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">上次保养时间</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.lastServicingTime || '--' }}</Col>
            </Row>
            </Col>
          </Row>
          <Row style="border-top: 1px solid #eee;border-bottom: 1px solid #eee">
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">闭模高度</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.closedMoldHeight || '--' }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">上次到本次点检冲数</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.spotCheckNum || '--' }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">模具重量(吨)</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.mmodWeight || '--' }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">总累计冲次数</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.sumQty || '--' }}</Col>
            </Row>
            </Col>
          </Row>
        </div>
      </div>
    </Card>
    <Card title="保养时间" class="detail-content-layout mt16">
      <div class="basic-info">
        <div class="basic-info-body">
          <Row style="border-top: 1px solid #eee;border-bottom: 1px solid #eee">
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">任务生成时间</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.taskCreateTime }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">保养开始时间</Col>
              <Col class="basic-info-body-item editWrap" span="24">{{ dataArr.taskBeginTime }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">保养结束时间</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.taskEndTime }}</Col>
            </Row>
            </Col>
            <Col span="6">
            <Row>
              <Col class="basic-info-body-label" span="24">保养人</Col>
              <Col class="basic-info-body-item" span="24">{{ dataArr.reviewName || '--' }}</Col>
            </Row>
            </Col>
          </Row>
        </div>
      </div>
    </Card>
    <Card title="协助保养人" class="mt16 detail-content-layout">
      <div class="basic-info">
        <div class="basic-info-title mb16">
          <Button v-if="!readonly && maintenanceStatus == 1" type="primary" style="height: 35px;" ghost shape="circle" icon="md-add"
            @click="openPersonnelSelectionModal">添加协助维修人
          </Button>
        </div>
        <div class="basic-info-body">
          <Table :columns="assisterColumns" :data="dataArr.assisterList">
            <template slot-scope="{ row,index }" slot="action" v-if="!readonly && maintenanceStatus == 1">
              <span class="icon" @click="deletePerson(row, index)">{{ $t('common.Delete') }}</span>
            </template>
          </Table>
        </div>
      </div>
    </Card>
    <Card title="保养内容" class="detail-content-layout mt16">
      <div class="basic-info">
        <div class="basic-info-body">
          <div class="contentTable">
            <!-- {{ dataArr.itemList }} -->
            <Table @on-column-width-resize="(a, b, c, d) => { onColumnWidthResize(a, b, c, d, 'maintenanceDetail0012') }"
              class="resizable-table" border ref="selection" :columns="contentColumns" :data="dataArr.itemList">
              <template slot-scope="{ row,index }" slot="action" >
                <span class="operationBtn" @click="checkInfo(row, 1, index)">{{ $t('maintenance.Tool') }}</span>
                <span class="operationBtn" @click="checkInfo(row, 2, index)">{{ $t('maintenance.Material') }}</span>
                <span class="operationBtn" @click="checkInfo(row, 3, index)">{{ $t('maintenance.Appendix') }}</span>
              </template>
              <template slot-scope="{row,index}" slot="result">
                <template v-if="!readonly && maintenanceStatus == 1">
                  <RadioGroup v-model="dataArr.itemList[index].result">
                    <Radio label="正常">正常</Radio>
                    <Radio label="异常">异常</Radio>
                  </RadioGroup>
                </template>
                <template v-else>{{ row.result }}</template>
                <!-- <template v-else>{{ row.resultStatus ? (row.resultStatus === 1 ? '正常' : '异常') : '' }}</template> -->
              </template>
              <template slot-scope="{row,index}" slot="resultRecord">
                <template v-if="!readonly && maintenanceStatus == 1">
                  <Input v-model="dataArr.itemList[index].resultRecord" clearable type="text" />
                </template>
                <template v-else>{{ row.resultRecord }}</template>
              </template>
            </Table>
          </div>
        </div>
      </div>
    </Card>

    <Card title="保养评分" class="detail-content-layout mt16" v-if="maintenanceStatus >= 2">
      <div class="basic-info">
        <div class="basic-info-body">
          <Row>
            <Col span="8">
            <Row>
              <Col class="basic-info-body-label" span="24"><span style="color: red">*</span>{{ $t('fault.ServiceAttitude')
              }}评分
              </Col>
              <Col class="basic-info-body-item" span="24">
              <Rate :disabled="maintenanceStatus !== '2'" v-model="detailObj.serveScore" />
              </Col>
            </Row>
            </Col>
          </Row>
          <Row>
            <Col span="8">
            <Row>
              <Col class="basic-info-body-label" span="24"><span style="color: red">*</span>{{
                $t('fault.TechnicalCompetence') }}评分
              </Col>
              <Col class="basic-info-body-item" span="24">
              <Rate :disabled="maintenanceStatus !== '2'" v-model="detailObj.technologyScore" />
              </Col>
            </Row>
            </Col>
          </Row>
          <Row>
            <Col span="8">
            <Row>
              <Col class="basic-info-body-label" span="24"><span style="color: red">*</span>{{ $t('fault.ResponseSpeed')
              }}评分
              </Col>
              <Col class="basic-info-body-item" span="24">
              <Rate :disabled="maintenanceStatus !== '2'" v-model="detailObj.responseScore" />
              </Col>
            </Row>
            </Col>
          </Row>
          <Row>
            <Col span="8">
            <Row>
              <Col class="basic-info-body-label" span="24"><span style="color: red">*</span>评语
              </Col><!--响应速度-->
              <Col class="basic-info-body-item" span="24">
              <Input v-model="detailObj.evaluate" :border="false" :disabled="maintenanceStatus !== '2'"
                :placeholder="`${$t('common.inputInfo')}`" />
              </Col>
            </Row>
            </Col>
          </Row>

        </div>
      </div>
    </Card>

    <template>
      <gallery :images="galleryImages" :index="galleryIndex" @close="galleryIndex = null"></gallery>
    </template>
    <bottom-handle-wrap>
      <Button @click="backPage">{{ $t('common.Cancel') }}</Button>
      <template v-if="readonly !== true">
        <template v-if="maintenanceStatus == 1">
          <Button type="primary" @click="checkManitain">保养完成</Button>
        </template>
        <template v-if="maintenanceStatus == 2">
          <Button type="primary" @click="accept">完成确认</Button>
        </template>
      </template>
    </bottom-handle-wrap>

    <personnel-selection-modal ref="personnelSelectionModal" :title="$t('请选择') + $t('人员')" :checkbox="true"
      @handleOk="selectPersonnel">
    </personnel-selection-modal>

    <Modal :mask-closable="false" v-model="backFaultCodeShowF" class="modal-title-layout" :title="`${$t('fault.ConfiRejected')}`">
      <div class="icon red" style="margin: 23px auto 16px !important;">
        <i class="iconfont zy-common-shibai1"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.Pleasereject') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="backFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
      </div>
    </Modal>

    <Modal :mask-closable="false" width="800px" v-model="handleEditRecordStatus" class="modal-title-layout" :title="`${$t('修改记录')}`">
      <Table ellipsis ref="selection" height="500" :columns="editRecordColumnList" :data="editRecordList">
      </Table>
      <div slot="footer">
        <Button type="primary" @click="handleEditRecordStatus = false">{{ $t('确认') }}</Button>
      </div>
    </Modal>


    <Modal :mask-closable="false" v-model="visible" :title="`${$t('common.Detail')}`" class="checkContentModal" width='1200' footer-hide>
      <contentDetail :planMaterialList="materialList" :planToolList="toolList"></contentDetail>
    </Modal>

    <Modal :mask-closable="false" v-model="useTableStatus" :title="`${$t('maintenance.usetools')}`" class="checkContentModal" width='900'
      footer-hide>
      <div class="materBox">
        <div class="icon" @click="handleTool('add')" v-if="!readonly">
          <Icon type="md-add" color="#187BDB" />{{ $t('maintenance.AddTools') }}
        </div>
        <Table @on-column-width-resize="(a, b, c, d) => { onColumnWidthResize(a, b, c, d, 'UsetoolsA001') }"
          class="resizable-table" border :columns="useTableColumn" :data="useTablelist">
          <template slot-scope="{row}" slot="action">
            <span class="operationBtn" @click="toolEdit(row)">{{ $t('common.Edit') }}</span>
            <span class="operationBtn" @click="toolDelete(row, index)">{{ $t('common.Delete') }}</span>
          </template>
        </Table>
      </div>
    </Modal>

    <Modal :mask-closable="false" v-model="fileTableStatus" :title="`${$t('ledger.attachmentinformation')}`" class="checkContentModal"
      width='900' footer-hide>
      <div class="imgBoxlist">
        <template v-if="!readonly">
            <Row :gutter="20">
              <div class="imageList">
                <Col :span="4" class="item" v-for="(file, index) in fileTablelist" :key="index"
                  @click="previewClicjk(file, index, fileTablelist)">
                  <img v-if="util.fileType(file.fileName) === 'image'" :src="file.fileUrl" alt="" />
                  <video v-else-if="util.fileType(file.fileName) === 'video'" preload="auto" loop autoplay muted>
                    <source :src="util.filePathToUrl(
                      file.filePath || file.filepath
                    )
                      " type="video/mp4" />
                  </video>
                  <span v-else class="fileSty">{{ file.fileName }}</span>
                  <Icon
                      type="ios-close-circle"
                      class="delIcon"
                      @click.stop="deleteImg(index)"
                    />
                </Col>
              </div>
              <Col :span="4">
              <div class="itemCol videoCol">
                <van-uploader accept="*" :show-upload-list="false" :after-read="afterRead">
                  <template #preview-cover="{ file }">
                    <span v-if="false">{{ file }}</span>
                    <span class="text">{{ $t('maintenance.New') }}</span>
                  </template>
                </van-uploader>
              </div>
              </Col>
            </Row>
        </template>
        <template v-else>
          <template v-if="fileTablelist && fileTablelist.length">
            <div class="videoList">
              <Row>
                <Col :span="4" v-for="(list, index) in fileTablelist" :key="index">
                <div class="itemCol">
                  <span class="item" @click="previewClicjk(list, index, fileTablelist, 'target')">
                    <template v-if="!list.filePath.includes('video')">
                      <img :src="util.filePathToUrl(list.filePath)" alt="" />
                    </template>
                    <template v-else>
                      <video preload="auto" loop autoplay muted>
                        <source :src="util.filePathToUrl(list.filePath)" type="video/mp4">
                      </video>
                    </template>
                  </span>
                </div>
                </Col>
              </Row>
            </div>
          </template>
        </template>
      </div>
    </Modal>


    <!-- <Modal :mask-closable="false" v-model="sopStatus" :title="`${$t('保养SOP')}`" class="checkContentModal" width='900' footer-hide>
      <div class="imgBoxlist">
        <div class="videoList">
          <Row>
            <Col :span="4" v-for="(list, index) in sopRow.attachment" :key="index">
            <div class="itemCol">
              <span class="item" @click="previewClicjk(list, index, sopRow.attachment)">
                <template v-if="util.fileType(list.filePath) === 'image'">
                  <img :src="util.filePathToUrl(list.filePath)" alt="" />
                </template>
                <template v-else-if="util.fileType(list.filePath) === 'video'">
                  <video preload="auto" loop autoplay muted>
                    <source :src="util.filePathToUrl(list.filePath)" type="video/mp4">
                  </video>
                </template>
                <template v-else>
                  <span class="fileSty">
                    <span>{{ list.fileName }}</span>
                  </span>
                </template>
              </span>
            </div>
            </Col>
          </Row>
        </div>
      </div>
    </Modal> -->


    <Modal :mask-closable="false" v-model="materTableStatus" id="materTableStatus" @on-visible-change="toolvisibleChange"
      :title="`${$t('maintenance.Usematerial')}`" class="checkContentModal" width='900'>
      <div class="materBox">
        <div class="icon" @click="handleMaterial" v-if="!readonly">
          <Icon type="md-add" color="#187BDB" />{{ $t('maintenance.Addmaterial') }}
        </div>
        <Table class="resizable-table" border :columns="contentColumnsInfo" :data="materTablelist">
          <template slot-scope="{row}" slot="action" v-if="!readonly">
            <span class="operationBtn" @click="materEdit(row)">{{ $t('common.Edit') }}</span>
            <span class="operationBtn" @click="materDelete(row, index)">{{ $t('common.Delete') }}</span>
          </template>
        </Table>
      </div>
      <div slot="footer">
        <Button type="default" @click="materTableStatus = false">{{ $t('common.Cancle') }}</Button>
      </div>
    </Modal>
    <!--   添加工具-->
    <Modal :mask-closable="false" v-model="toollVisible" width="640" @on-visible-change="toolvisibleChange" class="addModal modal-content-layout"
      :title="`${$t('maintenance.usetools')}`">
      <div class="addProject">
        <Form label-position="top">
          <FormItem :label="$t('maintenance.ToolName')" required>
            <template v-if="toolStatus == 'add'">
              <Select filterable clearable v-model="tableTool.toolName" :remote-method="toolNoChange"
                @on-change="toolChange">
                <Option v-for="item in toolNoList" :value="item.materialName" :label="item.materialName"
                  :key="item.deviceMId" />
              </Select>
            </template>
            <template v-else>
              <Input disabled v-model="tableTool.toolName" />
            </template>
          </FormItem>
          <FormItem  :label="$t('maintenance.Materialno')"  required>
            <Input class="inputWrapper" disabled v-model="tableTool.toolCode" />
          </FormItem>
          <FormItem :label="$t('保管方式')">
            <Input class="inputWrapper" v-model="tableTool.toolMode" />
          </FormItem>
          <FormItem :label="$t('maintenance.Amount')" required>
            <InputNumber :min="1" :disabled="tableTool.numStatus" v-model="tableTool.toolNum" />
          </FormItem>
        </Form>
      </div>

      <div slot="footer">
        <Button type="default" @click="toollVisible = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="toolTableobj">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <!--    添加物料-->
    <Modal :mask-closable="false" v-model="materialVisible" width="640" @on-visible-change="visibleChange" class="addModal modal-content-layout"
      :title="`${$t('maintenance.materialinfo')}`">
      <div class="addProject">
        <Form label-position="top">
          <FormItem :label="$t('common.GoodsName')" required>
            <template v-if="materiaStatus == 'add'">
              <Select filterable clearable v-model="tableMaterial.goodsName" :remote-method="materielNoChange"
                @on-change="materieChange">
                <Option v-for="(item,index) in materielNoList" :value="item.materialName" :label="item.materialName"
                  :key="index" />
              </Select>
            </template>
            <template v-else>
              <Input disabled v-model="tableMaterial.goodsName" />
            </template>
          </FormItem>
          <FormItem :label="$t('maintenance.MaterialnoInfo')"  required>
            <Input class="inputWrapper" disabled v-model="tableMaterial.code" />
          </FormItem>
          <FormItem :label="$t('common.Specification')">
            <Input class="inputWrapper" disabled v-model="tableMaterial.specification" />
          </FormItem>
          <FormItem :label="$t('spareParts.quantity')" required>
            <InputNumber style="width: 100%;" :min="1" v-model="tableMaterial.qty" />
          </FormItem>
        </Form>
      </div>

      <div slot="footer">
        <Button type="default" @click="materialVisible = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="materiaTableobj">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>

  </div>
</template>
  
<script>
import VueGallery from 'vue-gallery'
// import searchAndSelectComponent from '@/components/searchAndSelect.vue'
// import sparePartsPurchasingRecords from '@/views/fault/workOrderHall/modules/sparePartsPurchasingRecords'
import PersonnelSelectionModal from '@/components/PersonnelSelectionModal.vue'
import moment from 'moment'
import { fileUpload } from "@/api/maintenance";

export default {
  name: 'dataRepairDetail',
  components: {
    gallery: VueGallery,
    // searchAndSelectComponent,
    // sparePartsPurchasingRecords,
    PersonnelSelectionModal
  },
  computed: {
    upgradeClass() {
      // console.log(this.params.upgradeReason,);
      const info = this.upgradeList.filter(v => v.upgradeReason === this.params.upgradeReason)[0]
      // console.log(info);/
      return info ? info.grade : ''
    },
    upgradeRole() {
      const info = this.upgradeList.filter(v => v.upgradeReason === this.params.upgradeReason)[0]
      return info ? [info.upgradeRole, info.roleId] : ['', null]
    }
  },
  created() {
    // this.show(this.$route.query.id, '2')
    this.show(this.$route.query.id + '', this.$route.query.status + '')
    this.getDetailInfo(this.id)
    // this.getFaultType()
    // this.getupgradeList()
    // this.getFaultTypeList()
    // this.getDistributionRecord()
    // this.getUpgradeRecordList()
    // this.getBwList();
  },
  data() {
    return {
      id: null,
      index: 0,
      maintenanceStatus: '',
      tarGetObj: {},
      dataArr: {},
      
      readonly: false,
      contentColumns: [
        {
          title: `${this.$t('maintenance.MaintenanceItem')}`,
          key: 'itemProject',
          align: 'center',
          width: 300,
          tooltip: true,
          resizable: true,
        },
        {
          title: '基准',
          key: 'itemBase',
          align: 'center',
          width: 180,
          tooltip: true,
          resizable: true
        },
        {
          title: '标准工时（s）',
          key: 'unitTime',
          align: 'center',
          width: 180,
          tooltip: true,
          resizable: true
        },
        {
          title: '方法',
          key: 'itemMethod',
          align: 'center',
          width: 300,
          tooltip: true,
          resizable: true
        },
        {
          title: `${this.$t('maintenance.maintainresults')}`,
          key: 'result',
          align: 'center',
          width: 200,
          slot: 'result',
          tooltip: true,
          resizable: true,
          renderHeader: (h) => {
            return h('div', this.showStatus ? [
              h('Checkbox', {
                style: {
                  display: "inline-block",
                  margin: '0 5px 0 0 !important'
                },
                on: {
                  'on-change': (val) => {
                    this.changeradio(val)
                  }
                }
              }),
              h('span', {
                domProps: {
                  innerHTML: `${this.$t('maintenance.maintainresults')}`
                }
              })
            ] : [h('span', `${this.$t('maintenance.maintainresults')}`)])
          }
        },
        {
          title: `${this.$t('maintenance.resultrecord')}`,
          key: 'resultRecord',
          slot: 'resultRecord',
          align: 'center',
          width: 300,
          tooltip: true,
          resizable: true
        },
        // {
        //   title: `${this.$t('保养SOP')}`,
        //   key: 'resultValue',
        //   align: 'center',
        //   minWidth: 200,
        //   resizable: true, tooltip: true,
        //   render: (h, params) => {
        //     if (params.row.attachment && params.row.attachment.length) {
        //       return h('div', [
        //         h('span', {
        //           style: {
        //             color: '#187BDB',
        //             cursor: 'pointer'
        //           },
        //           on: {
        //             click: () => {
        //               this.sopStatus = true
        //               this.sopRow = params.row
        //             }
        //           }
        //         }, '查看')
        //       ]);
        //     } else {
        //       return h('div', [
        //         h('span', '无')
        //       ])
        //     }
        //   }
        // },
        {
          title: `${this.$t('common.operation')}`, slot: 'action', width: 220, align: 'center', fixed: "right"
        },
      ],
      //工具弹窗和列表
      useTableStatus: false,
      useTablelist: [],
      useTableColumn: [
        {
          type: 'index',
          width: 90,
          title: `${this.$t('common.index')}`,
          align: 'center'
        },
        {
          title: `${this.$t('maintenance.ToolMaterialNo')}`,
          key: 'toolCode',
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('maintenance.Toolnames')}`,
          key: 'toolName',
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('spareParts.quantity')}`,
          key: 'qty',
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('保管方式')}`,
          key: 'toolMode',
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          key: 'action',
          align: 'center',
          slot: 'action'
        }
      ],
      toolStatus: 'add',
      toollVisible: false,
      tableTool: {},
      materTablelist: [],
      materTableStatus: false,
      toolList: [],
      contentColumnsInfo: [
        {
          type: 'index',
          width: 90,
          title: `${this.$t('common.index')}`,
          align: 'center'
        },
        {
          title: `${this.$t('maintenance.MaterialnoInfo')}`,
          key: 'code',
          align: 'center',
          width: 200,
          resizable: true
        },
        {
          title: `${this.$t('common.GoodsName')}`,
          key: 'goodsName',
          align: 'center',
          width: 200,
          resizable: true
        },
        {
          title: `${this.$t('spareParts.Specification')}`,
          key: 'specification',
          align: 'center',
          width: 200,
          resizable: true
        },
        {
          title: `${this.$t('spareParts.quantity')}`,
          key: 'qty',
          width: 200,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          key: 'action',
          align: 'center',
          fixed: 'right',
          width: 200,
          slot: 'action'
        }
      ],
      materialVisible: false,
      materiaStatus: 'add',
      tableMaterial: {},

      bwList: [],
      faultLevelList: ['A', 'B', 'C'],
      updatedata10: false,
      editRecordList: [],

      handleEditRecordStatus: false,
      analysisOfCausesEdit: false,
      backFaultCodeShowF: false,

      upgradeRecordList: [],
      assisterColumns: [
        {
          title: '姓名',
          key: 'name',
          align: 'center',
          minWidth: 120
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: 'action',
          align: 'center',
          minWidth: 200
        }
      ],
      galleryIndex: null,
      galleryImages: [],
      optionsdate: {
        disabledDate(date) {
          return date && date.getdata() > Date.now()
        }
      },
      setFileList: [],
      statusText: '',
      detailObj: {},

      makeDataSource: [],
      upgradeList: [],
      faultTypeList: [],
      endFileList: [],
      isRepairReject: false,
      reanalyzeObj: {
        whyList: [{ analyse: '' }, { analyse: '' }, { analyse: '' }, { analyse: '' }, { analyse: '' }]
      },
      userType: '',
      confirmedBy: false,
      materialList: [],
      toolNoList: [],
      materielNoList: [],
      fileTablelist: [],
      fileTableStatus: false,

    }
  },

  methods: {
    //根据状态控制
    show(id, type) {
      this.id = id;
      this.maintenanceStatus = type + '';
      if (this.$route.query.type == 'view') {
        this.readonly = true;
      } else if (this.maintenanceStatus == '1') {
        this.readonly = false;
      } else if (this.maintenanceStatus == '2') {
        this.readonly = false;
      } else this.readonly = true;
    },
    //获取保养详情数据
    getDetailInfo(id) {
      this.axios({
        method: 'get',
        url: '/dms/servicingPlan/selectPlanById',
        params: { id, }
      }).then(res => {
        if (res.code === 200) {
          this.dataArr = res.data;
          this.detailObj.responseScore = this.dataArr.responseScore;
          this.detailObj.technologyScore = this.dataArr.technologyScore;
          this.detailObj.serveScore = this.dataArr.serveScore;
          this.detailObj.evaluate = this.dataArr.evaluate;
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })
    },
    checkInfo(row, num, index) {
      console.log(row);
      this.index = index;
      switch (num) {
        case 1:
          this.useTablelist = row.toolList
          this.useTableStatus = true
          break;
        case 3:
          this.fileTablelist = row.fileList || []
          this.fileTableStatus = true
          break;
        case 2:
          this.materTablelist = row.materialList
          this.materTableStatus = true
          break;
      }
    },
    handleTool(toolStatus) {
      this.toolStatus = toolStatus
      this.tableTool = {
        num: 1
      }
      this.toolNoList = []
      this.toollVisible = true
    },
    deleteImg(index) {
      this.fileTablelist.splice(index, 1);
    },
    toolNoChange(val) {
      this.axios({
        method: 'post',
        url: '/dms/material/page',
        data: {
          pageNum: 1,
          pageSize: 99,
          materialName: val || null,
        }
      }).then(res => {
        if (res.code === 200) {
          this.toolNoList = res.data.records || [];
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    toolChange(val) {
      if (!val) {
        return
      }
      const obj = this.toolNoList.find(item => item.materialName == val)
      if (obj) {
        this.tableTool = {
          toolCode: obj.materialCode,
          toolName: obj.materialName,
          toolMode: '',
          qty: 1
        }
      }
    },
    toolTableobj() {
      if (!this.tableTool.toolCode) {
        this.$Message.error(({ content: '请填写工具物料号!', duration: 3, closable: true }));
        return;
      }
      if (!this.tableTool.toolName) {
        this.$Message.error(({ content: '请填写工具名称!', duration: 3, closable: true }));
        return;
      }
      if (!this.tableTool.toolMode) {
        this.$Message.error(({ content: '请填写保管方式!', duration: 3, closable: true }));
        return;
      }
      if (!this.tableTool.qty) {
        this.$Message.error(({ content: '请填写数量!', duration: 3, closable: true }));
        return;
      }
      if (this.toolStatus !== 'edit') {
        const flag = this.dataArr.itemList[this.index].toolList.find(val => val.toolCode === this.tableTool.toolCode)
        if (flag) {
          this.$Message.error(({ content: '该工具已添加', duration: 3, closable: true }));
          return
        } else {
          this.dataArr.itemList[this.index].toolList.push(this.tableTool);
          this.useTablelist = this.dataArr.itemList[this.index].toolList
          this.toollVisible = false;
        }
      } else {
        const index = this.dataArr.itemList[this.index].toolList.findIndex(val => val.toolCode === this.tableTool.toolCode)
        this.dataArr.itemList[this.index].toolList[index] = this.tableTool;
        this.toollVisible = false;
      }
    },
    toolEdit(row) {
      this.toolStatus = 'edit'
      this.tableTool = row
      this.toollVisible = true
    },
    toolDelete(row, index) {
      this.dataArr.itemList[this.index].toolList.splice(index - 1, 1)
      this.useTablelist = this.dataArr.itemList[this.index].toolList
    },
    materEdit(row) {
      this.materiaStatus = 'edit'
      this.tableMaterial = row
      this.materialVisible = true
    },
    materDelete(row, index) {
      this.dataArr.itemList[this.index].materialList.splice(index - 1, 1)
      this.materTablelist = this.dataArr.itemList[this.index].materialList
    },
    handleMaterial() {
      this.tableMaterial = {
        qty: 1
      }
      this.materielNoList = []
      this.materialVisible = true
    },
    debounceSerach(fn, delay) {
      let _this = this
      return function f(...args) {
        if (_this.timeID) {
          clearTimeout(_this.timeID);
        }
        _this.timeID = setTimeout(() => {
          fn(args);
        }, delay);
      };
    },
    materielNoChange(val, value) {
      if (val && this.materielNoList.find(item => item.materielName === val)) {
        return;
      }
      const fn = this.debounceSerach(() => {
        const params = {
          materialName: val,
          pageNum: 1,
          pageSize: 99,
        }
        this.axios({
          method: 'post',
          url: '/dms/material/page',
          data: { ...params }
        }).then(res => {
          if (res.code === 200) {
            this.materielNoList = res.data.records
          } else {
            this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
          }
        })
      }, 360)
      fn()
    },
    materieChange(val) {
      if (!val) {
        return
      }
      const obj = this.materielNoList.find(item => item.materialName == val)
      if (obj) {
        this.tableMaterial = {
          code: obj.materialCode,
          goodsName: obj.materialName,
          specification: obj.materialModel,
          qty: this.tableMaterial.qty
        }
      }
    },
    materiaTableobj() {
      if (!this.tableMaterial.code) {
        this.$Message.error(({ content: '请填写物料号!', duration: 3, closable: true }));
        return;
      }
      if (!this.tableMaterial.goodsName) {
        this.$Message.error(({ content: '请填写品名!', duration: 3, closable: true }));
        return;
      }
      // if (!this.tableMaterial.specification) {
      //   this.$Message.error(({ content: '请填写规格!', duration: 3, closable: true }));
      //   return;
      // }
      if (!this.tableMaterial.qty) {
        this.$Message.error(({ content: '请填写数量!', duration: 3, closable: true }));
        return;
      }
      if (this.materiaStatus !== 'edit') {
        const flag = this.materTablelist.some(val => val.code === this.tableMaterial.code)
        if (flag) {
          this.$Message.error(({ content: '该物料已添加', duration: 3, closable: true }));
          return
        } else {
          this.dataArr.itemList[this.index].materialList.push(this.tableMaterial);
          this.materTablelist = this.dataArr.itemList[this.index].materialList
          this.materialVisible = false;
        }
      } else {
        const index = this.dataArr.itemList[this.index].materialList.findIndex(val => val.code === this.tableMaterial.toolcodeCode)
        this.dataArr.itemList[this.index].materialList[index] = this.tableMaterial;
        this.materialVisible = false;
      }
    },
    afterRead(file) {
      // console.log(file)
      // if(file.file.type.indexOf('video') !== -1 || file.file.type.indexOf('image') !== -1){
      let formData = new FormData();
      formData.append("dir", "device");
      // console.log(this.dataURLtoFileFun(file.content, "file.jpg"))
      // console.log(file)
      formData.append("file", file.file);
      // if (file.file.name.indexOf('jpg') !== -1){
      //   formData.append("file", this.dataURLtoFileFun(file.content, "file.jpg"));
      // }
      // if (file.file.name.indexOf('png') !== -1){
      //   formData.append("file", this.dataURLtoFileFun(file.content, "file.png"));
      // }
      // if (file.file.name.indexOf('mp4') !== -1){
      //   formData.append("file", this.dataURLtoFileFun(file.content, "file.video"));
      // }
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      // console.log(formData)
      fileUpload(formData, config).then((res) => {
        if (res.code == 200) {
          if (!res.data.fileLength) {
            return;
          }
          const data = [res.data].map((val) => ({
            fileName: val.fileName,
            filePath: val.filepath,
            fileUrl: val.fileUrl,
            previewPath: val.previewPath,
          }));
          console.log(data);
          console.log(this.fileTablelist);
          this.fileTablelist.push(data[0]);

          // this.axios({
          //   method: 'post',
          //   url: '/dms/dcmAttachment/itemUpload',
          //   data
          // }).then(res=>{
          //   if (res.code == 200){
          //     this.$Message.success(res.msg)
          //   }else {
          //     this.$Message.error(res.msg)
          //   }
          // })
        }
      });
      // }else{
      //   this.$Message.error('只能上传视频/图片')
      // }
    },

    updateFaultVerification(params) {
      this.axios({
        method: 'post',
        url: '/dms/workOrder/updateFaultVerification',
        data: { ...params, dmsMaintainId: this.$route.query.id }
      }).then(res => {
        if (res.code === 200) {
          this.getDetailInfo()
          this.$Message.success({ content: res.msg, duration: 6, closable: true })
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })
    },
    openPersonnelSelectionModal(item) {
      this.userType = item
      this.$refs['personnelSelectionModal'].open()
    },
    selectPersonnel(users) {
      const usersArr = users.map(item => {
        return {
          name: item.realname,
          userId: item.id
        }
      })
      const arr=usersArr.concat(this.dataArr.assisterList)
      let deWeightThree = () => {
        // let name = 'userId';
        let map = new Map();
        for (let item of arr) {
          if (!map.has(item.userId)) {
            map.set(item.userId, item);
          }
        }
        return [...map.values()];
      }
      this.dataArr.assisterList = deWeightThree();
      // this.$set(this.dataArr, 'assisterList', usersArr);
      // let assisters = []
      // let userIds = []
      // users.forEach(item => {
      //   assisters.push(item.empno + '-' + item.realname)
      //   userIds.push(item.id)
      // })
      // if (this.userType === 1) {
      //   this.reanalyzeObj.principalStr = assisters.join(';')
      //   this.reanalyzeObj.principal = userIds
      // } else if (this.userType === 2) {
      //   this.reanalyzeObj.participantStr = assisters.join(';')
      //   this.reanalyzeObj.participant = userIds
      // } else {
      //   this.params.assister = assisters.join(';')
      //   this.params.userIds = userIds
      // }
      // this.$forceUpdate()
      this.$refs['personnelSelectionModal'].close()
    },
    getLabelFormValue(list, value) {
      if (!value || !(Array.isArray(list) && list.length > 0)) return ''
      const obj = list.find(item => item.value == value)
      return obj.label
    },
    backPage() {
      sessionStorage.setItem('dataRepairStatus', this.$route.query.status)
      this.$router.go(-1)
    },
    previewClicjk(item, index) {
      // console.log('这是/*什么')
      // console.log(this.detailObj.*/attachmentDTOs1)
      this.galleryIndex = index
      let arr = this.detailObj.attachmentDTOs1
      this.galleryImages = arr.map(val => {
        if (val.filePath.includes('video')) {
          val.filetype = 'video/mp4'
        }
        if (val.filePath.includes('jpg')) {
          val.filetype = 'image/jpeg'
        }
        let params = {
          type: val.filetype,
          href: this.util.filePathToUrl(val.filePath)
        }

        return params
      })
    },
    handleClose(val, type) {
      if (!val) {
        this[type] = false
      }
    },

    //获取升级数据
    getupgradeList() {
      this.axios({
        method: 'post',
        url: '/dms/upgrade/selectUpgrade',
        data: { upgradeType: '1' }
      }).then(res => {
        if (res.code === 200) {
          this.upgradeList = res.data
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })
    },

    //获取故障类型数据
    getFaultTypeList() {
      this.axios({
        method: 'get',
        url: '/dms/faultCategory/dictList',
        params: {
          name: '故障类型'
        }
      }).then(res => {
        this.faultTypeList = res.data || []
      })
    },
    getBwList() {
      this.axios({
        method: 'get',
        url: '/dms/faultCategory/dictList',
        params: {
          name: '部件'
        }
      }).then(res => {
        if (res.code === 200) {
          this.bwList = res.data
        }
      })
    },
    // 验收
    accept() {
      if (!this.detailObj.serveScore) {
        this.$Message.warning({ content: this.$t('服务态度评分不能为空'), duration: 6, closable: true })
        return
      }
      if (!this.detailObj.technologyScore) {
        this.$Message.warning({ content: this.$t('技术能力评分不能为空'), duration: 6, closable: true })
        return
      }
      if (!this.detailObj.responseScore) {
        this.$Message.warning({ content: this.$t('响应速度评分不能为空'), duration: 6, closable: true })
        return
      }

      if (!this.detailObj.evaluate) {
        this.$Message.warning({ content: this.$t('请输入评语'), duration: 6, closable: true })
        return
      }

      this.axios({
        method: 'post',
        url: '/dms/servicingTask/accept',
        data: {
          id: this.id,
          ...this.detailObj
        }
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg)
          this.backPage();
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })
    },
    // 完成保养
    checkManitain() {
      this.axios({
        method: 'post',
        url: '/dms/servicingTask/complete',
        data: this.dataArr
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg)
          this.backPage();
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })


    },
    maintainOutConfirmRejectBtn() {
      this.backFaultCodeShowF = true
    },
    handleRepairOutsourcingReject() {
      this.backFaultCodeShowF = true
      this.isRepairReject = true
    },
    //文件上传
    handleBeforeUpload(file) {
      let formData = new FormData()
      formData.append('dir', 'device')
      formData.append('file', file)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.axios({
        method: 'post',
        url: '/fileServer/upload',
        data: formData,
        config
      }).then(res => {
        if (res.code == 200) {
          this.setFileList.push({
            fileName: res.data.fileName,
            filePath: res.data.filepath,
            fileUrl: res.data.fileUrl
          })
        }
      })
      return false
    },
    //文件删除
    delFileList(e, i, end = false) {
      e.stopPropagation()
      if (end) {
        this.endFileList.splice(i, 1)
        return
      }
      this.setFileList.splice(i, 1)
    },
    handlePreview(item) {
      if (item.filePath) {
        window.open(this.util.filePathToUrl(item.filePath))
      }
    },
    // 添加备件
    handleAddDevice() {
      this.$refs.addMaterial.show()
    },
    // 编辑备件
    editMaterial(row) {
      this.$refs.addMaterial.show(this.detailObj.id, row, this.detailObj.deviceMId, this.detailObj.orgId)
    },
    // 删除备件
    deleteMaterial(row, index) {
      this.makeDataSource.splice(index, 1)
    },
    deletePerson(row, index) {
      this.dataArr.assisterList.splice(index, 1)
    },
    //文件上传
    handleBeforeUpload2(file) {
      let formData = new FormData()
      formData.append('dir', 'device')
      formData.append('file', file)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.axios({
        method: 'post',
        url: '/fileServer/upload',
        data: formData,
        config
      }).then(res => {
        if (res.code == 200) {
          this.endFileList.push({
            fileName: res.data.fileName,
            filePath: res.data.filepath,
            fileUrl: res.data.fileUrl
          })
        }
      })
      return false
    },


    toReview() {
      const { reviewdata, reviewResult, id } = this.detailObj

      if (!reviewResult) {
        this.$Message.warning({ content: this.$t('请输入维修结果'), duration: 6, closable: true })
        return
      }
      if (!reviewdata) {
        this.$Message.warning({ content: this.$t('请选择复核时间'), duration: 6, closable: true })
        return
      }
      let params = { reviewdata: moment(reviewdata).format('YYYY-MM-DD HH:mm:ss'), reviewResult, id }

      this.axios({
        method: 'post',
        url: '/dms/workOrder/review',
        data: params
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg)
          this.getDetailInfo()
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })
    },
    //添加物料
    addMaterialOk(data) {
      this.makeDataSource.push(data)
    },

  }
}
</script>
  
<style scoped lang="scss">
.imageList{
  position: relative;
  img{
    width: 100%;
    height: 80px;
  }
  .delIcon {
    position: absolute;
    right: -10px;
    top: -10px;
    color: red;
    font-size: 20px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
  }
}
.operationBtn {
  padding: 0 4px;
  color: #187BDB;
  cursor: pointer;
}

.materBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .operationBtn {
    cursor: pointer;
    margin: 0 10px;
    white-space: nowrap;
  }

  .operationBtn:hover {
    transition: all .3s linear;
    color: #035beb;
  }

  .icon {
    border: 1px solid #187bdb;
    border-radius: 30px;
    padding: 5px 20px 5px 20px;
    display: flex;
    align-items: center;
    //margin-left/*:*/ 20px;  
    color: #187bdb;
    margin: 0 16px 16px 16px;
    cursor: pointer;

    i {
      font-size: 20px;
      font-weight: bold;
    }
  }
}

.icon {
  cursor: pointer;

  &:first-child {
    margin-right: 20px;
  }
}

.basic-info {
  ::v-deep .ivu-select-selection {
    border: none;
  }

  .basic-info-title {

    span {
      display: inline-block;
      width: 7px;
      height: 24px;
      background: #187bdb;
    }

    h2 {
      display: inline-block;
      font-size: 16px;
      padding-left: 16px;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 5px;
        width: 7px;
        height: 24px;
        background: #187bdb;
      }
    }
  }
  .itemCol {
    height: 200px !important;
    width: 100%;
    background-color: #035beb !important;

    img {
      height: 100%;
      width: auto;
      cursor: pointer;
    }
  }

}
.basic-info-body {
    //margin: 15px 10px;
    color: #333;
    font-size: 13px;
    font-family: 'Arial Normal', 'Arial', sans-serif;
    font-weight: 400;
    border-left: 1px solid #eee;

    .editWrap {
      position: relative;

      .editTime {
        position: absolute;
        cursor: pointer;
        right: 10px;
        top: 0;
        color: #187bdb;
        font-size: 14px;

        .icon {
          font-size: 30px;
          vertical-align: middle;
        }
      }
    }

    .basic-info-body-label {
      display: inline-block;
      height: 40px;
      line-height: 40px;
      background: #f5f6f7;
      text-align: left;
      padding: 0 10px;
      border-right: 1px solid #eee;

      /*border-top: 1px solid #B6B7B7;*/
      /*border-bottom: 1px solid #B6B7B7;*/
      .fspan {
        cursor: pointer;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .basic-info-body-item {
      display: inline-block;
      height: 40px;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
      border-right: 1px solid #eee;
      // border-right: 1px solid #eee;

      .preview {
        position: absolute;
        right: 10px;
        top: 0;
        width: 40px;
        height: 40px;
        background: #eee;

        .preview-img {
          width: 40px;
          height: 40px;
          overflow: hidden;
        }
      }

      ::v-deep .ivu-upload-drag {
        display: flex;
        height: 40px;

        button {
          margin-top: 4px;
        }
      }

      .fileWrap {
        flex: 1;
        display: flex;
        overflow-y: scroll;
        flex-direction: column;

        &::-webkit-scrollbar {
          width: 4px;
        }
      }

      .file-list {
        padding-left: 20px;
      }
    }
  }
</style>
  